package com.deanlib.cabinet.ui.recyclerview;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @auther Dean
 * @create 2022/4/11
 */
public class GridItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount = 0;
    private int space = 0;//定义2个Item之间的距离
    private int leftSpace = 0;
    private int rightSpace = 0;

    public GridItemDecoration(Context context, int spanCount, int space){
        this.space = dip2px(context, space);
        this.spanCount = spanCount;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                               @NonNull RecyclerView parent,
                               @NonNull RecyclerView.State state) {
        /*//由于每行都只有2个，所以第一个都是spanCount的倍数，把左边距设为0
        if (parent.getChildLayoutPosition(view) %spanCount ==0) {
            outRect.set(0,space/2,space/2,space/2);
        }else {
            outRect.set(space/2,space/2,space/2,space/2);}*/
        if (parent.getAdapter()!=null) {
            int position = parent.getChildAdapterPosition(view);
            int totalCount = parent.getAdapter().getItemCount();
            int column = (position) % spanCount + 1;// 计算这个child 处于第几列

            outRect.top = space / 2;
            outRect.bottom = space / 2;
            //注意这里一定要先乘 后除  先除数因为小于1然后强转int后会为0
            outRect.left = (column - 1) * space / spanCount; //左侧为(当前条目数-1)/总条目数*divider宽度
            outRect.right = (spanCount - column) * space / spanCount; //右侧为(总条目数-当前条目数)/总条目数*divider宽度
        }
    }


    private int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
